package com.jwd.avmanager.parse;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jwd.avmanager.constant.Cmd;
import com.jwd.avmanager.entity.*;
import com.jwd.avmanager.pojo.*;
import com.jwd.avmanager.repository.BDMybais;
import com.jwd.avmanager.server.ClientManager;
import com.jwd.avmanager.util.ByteUtil;
import com.jwd.avmanager.util.DebugLogger;
import com.jwd.avmanager.util.ResponseFactory;
import com.jwd.avmanager.util.ResponseSendUtil;


import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;

import static com.jwd.avmanager.server.WebSocketHandler.URI_ATTRIBUTE_KEY;

public class ProtocolParserWS {
    Logger logger = LoggerFactory.getLogger(ProtocolParserWS.class);
    private ChannelHandlerContext ctx;
    private BDMybais instance;

    public ProtocolParserWS(ChannelHandlerContext handlerContext) {
        this.ctx = handlerContext;
        this.instance = BDMybais.getInstance();
    }

    public void parseMessage(Message packet) {
        DebugLogger.info("packet.getCmd():" + packet.getCmd());
        if(Cmd.CMD_IN_WEB_SOCKET_LOGIN != packet.getCmd()){
            String surl = ctx.channel().attr(URI_ATTRIBUTE_KEY).get();
            DebugLogger.info("客户端连接URL" + surl);
            String[] uriArray = surl.split("/");
            Map<String, Object> map1 = new HashMap();
            if (uriArray.length >= 3) {
                String uLoginName = uriArray[2];
                WebSocketInfo webSocketInfo = ClientManager.getInstance().getWebSocketInfo(uLoginName);
                if(webSocketInfo == null){
                    DebugLogger.err(logger,packet.getUserID()+ " <-- packet.getUserID() Abnormal request connection");      //异常请求连接
                    ctx.close();
                    return;
                }
            }
        }
        switch (packet.getCmd()) {
            //TODO 登录
            case Cmd.CMD_IN_WEB_SOCKET_LOGIN:
                DebugLogger.info("web登录");
                socketLogin(packet);
                //解析登录信令
                break;
            //TODO 退出登录
            case Cmd.CMD_IN_WEB_SOCKET_EXIT_LOGIN:
                DebugLogger.info("webs退出登录");
                socketExitLogin(packet);
                //解析登录信令
                break;
            case Cmd.CMD_IN_WEB_SOCKET_HEARTBEAT:
                DebugLogger.info("web端发送心跳");
                heartbeat(packet);
                //解析登录信令
                break;
            case Cmd.CMD_IN_WEB_SOCKET_WEB_GPS:
                DebugLogger.info("web端请求设备端发送GPS");
                serverGPS(packet);
                //解析登录信令
                break;
            case Cmd.CMD_IN_WEB_SOCKET_VIDEO_CALL:
                DebugLogger.info("视频聊天");
                videoCall(packet);
                //解析登录信令
                break;
            case Cmd.CMD_IN_WEB_SOCKET_VIDEO_CCTV:
                DebugLogger.info("视频监控");
                videoCCTV(packet);
                //解析登录信令
                break;
            case Cmd.CMD_IN_WEB_USER_GET_FILE:
                DebugLogger.info("获取用户下载文件");
                getDownloadFile(packet);
                //解析登录信令
                break;
            case Cmd.CMD_IN_WEB_SOCKET_JOIN_WEBRTC:
                DebugLogger.info("WS_ 加入WebRTC房间");
                join_quit(packet, 1);
                //解析登录信令
                break;
            case Cmd.CMD_IN_WEB_SOCKET_QUIT_WEBRTC:
                DebugLogger.info("WS_ 退出WebRTC房间");
                join_quit(packet, 0);
                //解析登录信令
                break;
            case Cmd.CMD_IN_WEB_SHOOT_FILE_LIST:
                DebugLogger.info("服务器请求返回执法仪的当前拍摄的文件列表");
                shootFileList(packet);
                //解析登录信令
                break;
            case Cmd.CMD_IN_WEB_CLOSE_FILE_LIST:
                DebugLogger.info("关闭文件获取列表清空缓存");
                closeFileList(packet);
                //解析登录信令
                break;
            case Cmd.CMD_IN_WEB_PUT_FILE_LIST:
                DebugLogger.info("web端请求上传文件的列表");
                try {
                    putFileList(packet);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                    DebugLogger.err(logger, packet.getUserID()+ " <-- packet.getUserID() putFileList CMD_IN_WEB_PUT_FILE_LIST: " + e);
                }
                //解析登录信令
                break;
            case Cmd.CMD_IN_WEB_SHOOT_CHAT_FILE:
                DebugLogger.info("发服务发短信来了");
                try {
                    shootChatFile(packet);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                    DebugLogger.err(logger, packet.getUserID()+ " <-- packet.getUserID() shootChatFile CMD_IN_WEB_SHOOT_CHAT_FILE: " + e);
                }
                //解析登录信令
                break;
            case Cmd.CMD_IN_WEB_VIDEO_MONITOR_RTMP:
                DebugLogger.info("发送监听的rtmp流的命令  5028");
                try {

                    videoMonitorRtmp(packet);

                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                    DebugLogger.err(logger, packet.getUserID()+ " <-- packet.getUserID() videoMonitorRtmp CMD_IN_WEB_VIDEO_MONITOR_RTMP: " + e);
                }
                //解析登录信令
                break;
            case Cmd.CMD_IN_WEB_VIDEO_STOP_RTMP:
                DebugLogger.info("服务器发送停止监听rtmp流的命令 5029");
                try {

                    videoStopRtmp(packet);
                } catch (Exception e) {
                    e.printStackTrace();
                    DebugLogger.err(logger, packet.getUserID()+ " <-- packet.getUserID() videoStopRtmp CMD_IN_WEB_VIDEO_STOP_RTMP: " + e);//参数异常

                }
            case Cmd.CMD_IN_WEB_SHOOT_MONITOR_RTMP:     //废除
                DebugLogger.info("发送监听的rtmp流的命令 5060");
                try {
                    shootMonitorRtmp(packet);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                    DebugLogger.err(logger, packet.getUserID()+ " <-- packet.getUserID() shootMonitorRtmp CMD_IN_WEB_SHOOT_MONITOR_RTMP: " + e);//参数异常

                }
                //解析登录信令
                break;
            case Cmd.CMD_IN_WEB_SHOOT_STOP_RTMP:    //废除
                DebugLogger.info("服务器发送停止监听rtmp流的命令5061");
                try {
                    shootStopRtmp(packet);
                } catch (Exception e) {
                    e.printStackTrace();
                    DebugLogger.err(logger, packet.getUserID()+ " <-- packet.getUserID() shootStopRtmpL CMD_IN_WEB_SHOOT_STOP_RTMP: " + e);//参数异常

                }
                //解析登录信令
                break;

            default:
                DebugLogger.err(logger,packet.getUserID()+ " <-- packet.getUserID() 未知信令_default_WS" + packet.getCmd());
                DebugLogger.err(logger,packet.toString());
                break;
        }

    }

    private void socketExitLogin(Message packet) {
        String value = JSON.toJSONString(packet.getValue());
        JSONObject body = JSON.parseObject(value);


        String uLoginName = null;
        try {
            uLoginName = body.getString("ulogin");
        } catch (Exception e) {
            DebugLogger.err(logger, packet.getUserID()+ " <-- packet.getUserID() shootMonitorRtmp json data exception: " + e);
            return;
        }
        if (uLoginName == null || uLoginName.isEmpty()) {
            Map<String, Object> map = new HashMap();
            map.put("state", 5);
            String valueJson = JSON.toJSONString(map);
            String str2 = "{\"devID\":\"" + 0 + "\",\"cmd\":\"" + Cmd.CMD_OUT_WEB_SOCKET_EXIT_LOGIN + "\",\"value\":" + valueJson + "}";
            ResponseSendUtil.writeAndFlushWs(str2, ctx);
            ctx.close();
            return;
        }
        ClientManager.getInstance().removeWebSocketMessage(uLoginName, 2, ctx);

    }

    private void socketLogin(Message packet) {


        String value = JSON.toJSONString(packet.getValue());
        JSONObject body = JSON.parseObject(value);

        String uLoginName = null;
        try {
            uLoginName = body.getString("uLoginName");
        } catch (Exception e) {
            DebugLogger.err(logger, packet.getUserID()+ " <-- packet.getUserID() socketLogin："+ e.getMessage());
            return;
        }
        //TODO ws 获取到 TOKEN
        //数据校验
        String surl = ctx.channel().attr(URI_ATTRIBUTE_KEY).get();
        DebugLogger.info("客户端断开URL" + surl);
        String[] uriArray = surl.split("/");
        Map<String, Object> map1 = new HashMap();
        if (uriArray.length >= 3) {
            System.out.println(uriArray[2] + "123");
            if (!uriArray[2].equals(uLoginName)) {
                //TODO 数据库  ID 校验 校验
                map1.put("state", 3);
                String valueJson = JSON.toJSONString(map1);
                String str2 = "{\"devID\":\"" + 0 + "\",\"cmd\":\"" + Cmd.CMD_OUT_WEB_SOCKET_LOGIN + "\",\"value\":" + valueJson + "}";
                ResponseSendUtil.writeAndFlushWs(str2, ctx);
                ctx.close();
                return;
            }

        } else {
            map1.put("state", 3);
            String valueJson = JSON.toJSONString(map1);
            String str2 = "{\"devID\":\"" + 0 + "\",\"cmd\":\"" + Cmd.CMD_OUT_WEB_SOCKET_LOGIN + "\",\"value\":" + valueJson + "}";
            ResponseSendUtil.writeAndFlushWs(str2, ctx);
            ctx.close();
            return;
        }
        //查询用户是否存在

        Map<String, Object> map = new HashMap();
        if (uLoginName == null || uLoginName.isEmpty()) {
            map.put("state", 5);
            String valueJson = JSON.toJSONString(map);
            String str2 = "{\"devID\":\"" + 0 + "\",\"cmd\":\"" + Cmd.CMD_OUT_WEB_SOCKET_LOGIN + "\",\"value\":" + valueJson + "}";
            ResponseSendUtil.writeAndFlushWs(str2, ctx);
            ctx.close();
            return;
        }
        Users users = instance.getuLoginName(uLoginName);
        if (users == null) {
            map.put("state", 1);
            String valueJson = JSON.toJSONString(map);
            String str2 = "{\"devID\":\"" + 0 + "\",\"cmd\":\"" + Cmd.CMD_OUT_WEB_SOCKET_LOGIN + "\",\"value\":" + valueJson + "}";
            ResponseSendUtil.writeAndFlushWs(str2, ctx);
            ctx.close();
            return;
        }

        //设备存在通知之前设备已被挤下线
        //缓存数据重置更新
        WebSocketInfo webSocketInfo = new WebSocketInfo();
        webSocketInfo.setAccount(uLoginName);
        webSocketInfo.setPass(uLoginName);
        webSocketInfo.setFileDevId(null);
        webSocketInfo.setFileSize(0);
        webSocketInfo.setCtx(ctx);
        DebugLogger.info(webSocketInfo.toString());
        ClientManager.getInstance().addwebSocketMessage(uLoginName, webSocketInfo);
        AlterUsetInfo alterUsetInfo = new AlterUsetInfo();
        alterUsetInfo.setuIsLogin(1);
        alterUsetInfo.setuLoginName(uLoginName);
        alterUsetInfo.setuLoginType(3);
        instance.setuLoginName(alterUsetInfo);

    }

    private void getDownloadFile(Message packet) {
        String value = JSON.toJSONString(packet.getValue());
        JSONObject body = JSON.parseObject(value);
        Integer devid = null;
        String devName = null;
        try {
            devid = body.getInteger("devId");
            devName = body.getString("devName");
        } catch (Exception e) {
            DebugLogger.err(logger, packet.getUserID()+ " <-- packet.getUserID() getDownloadFile json data exception: " + e);//参数异常

            return;
        }
        //查询设备id
        DebugLogger.info(logger, "dev_ID =" + devid + "JSON = " + value);
        DeviceInfo member = ClientManager.getInstance().getOnlineMemberByClientId(String.valueOf(devid));
        //查询设备名称
        if (member != null) {

            Map<String, Object> map = new HashMap();
            map.put("fileName", member.getFileName());
            String valueJson = JSON.toJSONString(map);
            String str2 = "{\"devID\":\"" + devid + "\",\"cmd\":\"" + Cmd.CMD_OUT_WEB_SOCKET_SET_FILE + "\",\"value\":" + valueJson + "}";
            DebugLogger.info(logger, str2);
            ResponseSendUtil.writeAndFlushWs(str2, ctx);
        }


    }

    private void videoStopRtmp(Message packet) {
        String value = JSON.toJSONString(packet.getValue());
        JSONObject body = JSON.parseObject(value);
        String devId = body.getString("devId");
        byte[] listResponse = ResponseFactory.getResponse(Cmd.CMD_OUT_STOP_RTMP, (short) 1, packet.getUserID());
        ChannelHandlerContext webSocket = ClientManager.getInstance().getSocketClient(devId);
        if (webSocket != null) {
            ResponseSendUtil.writeAndFlush(listResponse, webSocket);
        }
    }

    private void videoMonitorRtmp(Message packet) throws UnsupportedEncodingException {
        String value = JSON.toJSONString(packet.getValue());
        JSONObject body = JSON.parseObject(value);


        Integer rtmp_type = null; // 4 byte, rtmp类型，0 音视频；1 视频；2 音频
        int serial_no;    //  值越小优先级越高（1-100，1最高级别）。
        Integer id = null;   // 信息的内容 长度[128];

        String rtmp_add = null;   // 信息的内容 长度[128];
        try {
            rtmp_type = body.getInteger("rtmpType");
            serial_no = body.getInteger("serialNo");
            id = body.getInteger("devId");
            rtmp_add = body.getString("rtmpAddr");
        } catch (NumberFormatException e) {
            DebugLogger.err(logger, packet.getUserID()+ " <-- packet.getUserID() videoMonitorRtmp json data exception: " + e);
            return;
        }

        VideoServer video = instance.getVideoServerQry(53);
        long l = System.currentTimeMillis();
//        rtmp_add = "rtmp://"+video.getServerIP()+":"+video.getPort()+"/live/stream"+id+"?sign="+l;
        rtmp_add = ResponseFactory.CrtRTMPUrl(id, "stream", 1);
        byte[] intToBytes = ByteUtil.intToBytes(rtmp_type);// 4 byte, rtmp类型，0 音视频；1 视频；2 音频
        byte[] rtmpAddBytes = rtmp_add.getBytes("GB2312");
        byte[] bytes = new byte[132];
        System.arraycopy(intToBytes, 0, bytes, 0, intToBytes.length);
        System.arraycopy(rtmpAddBytes, 0, bytes, 4, rtmpAddBytes.length);


        byte[] listResponse = ResponseFactory.getListResponse(Cmd.CMD_OUT_UPLOADING_RTMP, (short) serial_no, packet.getUserID(), bytes);
        ChannelHandlerContext webSocket = ClientManager.getInstance().getSocketClient(String.valueOf(id));
        if (webSocket != null) {
            ResponseSendUtil.writeAndFlush(listResponse, webSocket);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("result", 1);
        map.put("rtmpurl", rtmp_add);
        map.put("devid", id);
        String valueJson = JSON.toJSONString(map);

        String fileOk = "{\"UserID\":\"" + packet.getUserID() + "\",\"cmd\":\"" + Cmd.CMD_OUT_WEB_SOCKET_VIDEO_FLOWING + "\",\"value\":" + valueJson + "}";
        ResponseSendUtil.writeAndFlushWs(fileOk, ctx);
    }

    private void heartbeat(Message packet) {

        //发给自己
        String strMy = "{\"devID\":\"" + packet.getUserID() + "\",\"cmd\":\"" + Cmd.CMD_OUT_WEB_SOCKET_HEARTBEAT + "\",\"value\":{}}";
        ResponseSendUtil.writeAndFlushWs(strMy, ctx);
    }

    private void shootStopRtmp(Message packet) {

        String value = JSON.toJSONString(packet.getValue());
        JSONObject body = JSON.parseObject(value);
        String devId = body.getString("devId");
        byte[] listResponse = ResponseFactory.getResponse(Cmd.CMD_OUT_STOP_MONITOR_RTMP, (short) 1, packet.getUserID());
        ChannelHandlerContext webSocket = ClientManager.getInstance().getSocketClient(devId);
        if (webSocket != null) {
            ResponseSendUtil.writeAndFlush(listResponse, webSocket);
        }
    }

    private void shootMonitorRtmp(Message packet) throws UnsupportedEncodingException {

        String value = JSON.toJSONString(packet.getValue());
        JSONObject body = JSON.parseObject(value);


        Integer rtmp_type = null; // 4 byte, rtmp类型，0 音视频；1 视频；2 音频
        int serial_no;    //  值越小优先级越高（1-100，1最高级别）。
        Integer id = null;   // 信息的内容 长度[128];

        String rtmp_add = null;   // 信息的内容 长度[128];
        try {
            rtmp_type = body.getInteger("rtmpType");
            serial_no = body.getInteger("serialNo");
            id = body.getInteger("devId");
            rtmp_add = body.getString("rtmpAddr");
        } catch (NumberFormatException e) {
            DebugLogger.err(logger, packet.getUserID()+ " <-- packet.getUserID() shootMonitorRtmp json data exception: " + e);
            return;
        }

        VideoServer video = instance.getVideoServerQry(53);
        long l = System.currentTimeMillis();
        rtmp_add = "rtmp://" + video.getServerIP() + ":" + video.getPort() + "/live/stream" + id + "?sign=" + l;

        byte[] intToBytes = ByteUtil.intToBytes(rtmp_type);// 4 byte, rtmp类型，0 音视频；1 视频；2 音频
        byte[] rtmpAddBytes = rtmp_add.getBytes("GB2312");
        byte[] bytes = new byte[132];
        System.arraycopy(intToBytes, 0, bytes, 0, intToBytes.length);
        System.arraycopy(rtmpAddBytes, 0, bytes, 4, rtmpAddBytes.length);


        byte[] listResponse = ResponseFactory.getListResponse(Cmd.CMD_OUT_BEGIN_MONITOR_RTMP, (short) serial_no, packet.getUserID(), bytes);
        ChannelHandlerContext webSocket = ClientManager.getInstance().getSocketClient(String.valueOf(id));
        if (webSocket != null) {
            ResponseSendUtil.writeAndFlush(listResponse, webSocket);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("result", 1);
        map.put("rtmpurl", rtmp_add);
        map.put("devid", id);
        String valueJson = JSON.toJSONString(map);

        String fileOk = "{\"UserID\":\"" + packet.getUserID() + "\",\"cmd\":\"" + Cmd.CMD_OUT_WEB_MONITOR_RTMP + "\",\"value\":" + valueJson + "}";
        ResponseSendUtil.writeAndFlushWs(fileOk, ctx);
    }

    private void shootChatFile(Message packet) throws UnsupportedEncodingException {
        String fileOk = null;

        String value = JSON.toJSONString(packet.getValue());
        JSONObject body = JSON.parseObject(value);


        Integer MsgType = null; // 信息类型；0 文本；1 照片；2 视频； 3 音频
        String Title = null;    // 信息的标题 长度[60]
        String Content = null;   // 信息的内容 长度[200];
        Integer obj = null;      // 聊天类型；1用户 ；2 群组
        Integer id = null;       //接收ID 设备id    或者  群组id
        try {
            MsgType = body.getInteger("msgType");
            Title = body.getString("title");
            Content = body.getString("content");
            obj = body.getInteger("obj");
            id = body.getInteger("id");
        } catch (Exception e) {
            DebugLogger.err(logger, packet.getUserID()+ " <-- packet.getUserID() shootChatFile JSON data exception: " + e);
            return;
        }

        byte[] intToBytes = ByteUtil.intToBytes(MsgType);// 4 byte, rtmp类型，0 音视频；1 视频；2 音频
        byte[] titleBytes = Title.getBytes("GB2312");
        byte[] contentBytes = Content.getBytes("GB2312");
        byte[] bytes = new byte[264];
        System.arraycopy(intToBytes, 0, bytes, 0, intToBytes.length);
        System.arraycopy(titleBytes, 0, bytes, 4, titleBytes.length);
        System.arraycopy(contentBytes, 0, bytes, 64, contentBytes.length);
        Map<String, Object> map = new HashMap<>();
        if (obj == 1) {         //1用户
            byte[] listResponse = ResponseFactory.getListResponse(Cmd.CMD_OUT_MESSAGE_DEVICE, (short) 1, packet.getUserID(), bytes);
            ChannelHandlerContext webSocket = ClientManager.getInstance().getSocketClient(String.valueOf(id));
            if (webSocket != null) {
                ResponseSendUtil.writeAndFlush(listResponse, webSocket);
                map.put("result", 1);
                String valueJson = JSON.toJSONString(map);
                fileOk = "{\"UserID\":\"" + packet.getUserID() + "\",\"cmd\":\"" + Cmd.CMD_OUT_WEB_SOCKET_FILE_TETRUN + "\",\"value\":" + valueJson + "}";
            }

        } else if (obj == 2) {  //2群组
            byte[] listResponse = ResponseFactory.getListResponse(Cmd.CMD_OUT_MESSAGE_DEVICE, (short) 1, packet.getUserID(), bytes);
            List<Audiostaffdevic> audioDevic = BDMybais.getInstance().getAudioDevic(id);
            for (Audiostaffdevic audiostaffdevic : audioDevic) {
                ChannelHandlerContext webSocket = ClientManager.getInstance().getSocketClient(String.valueOf(audiostaffdevic.getDevicid()));
                if (webSocket != null) {
                    ResponseSendUtil.writeAndFlush(listResponse, webSocket);

                }
            }
            map.put("result", 1);
            String valueJson = JSON.toJSONString(map);
            fileOk = "{\"UserID\":\"" + packet.getUserID() + "\",\"cmd\":\"" + Cmd.CMD_OUT_WEB_SOCKET_FILE_TETRUN + "\",\"value\":" + valueJson + "}";
        } else {
            map.put("result", 0);
            String valueJson = JSON.toJSONString(map);
            fileOk = "{\"UserID\":\"" + packet.getUserID() + "\",\"cmd\":\"" + Cmd.CMD_OUT_WEB_SOCKET_FILE_TETRUN + "\",\"value\":" + valueJson + "}";
        }

        ResponseSendUtil.writeAndFlushWs(fileOk, ctx);

    }


    private void videoCCTV(Message packet) {
        String value = JSON.toJSONString(packet.getValue());
        JSONObject body = JSON.parseObject(value);
        Integer DevIdx = null;
        String UserName = null;
        try {
            DevIdx = body.getInteger("devId");
            UserName = body.getString("userName");
        } catch (Exception e) {
            DebugLogger.err(logger, packet.getUserID()+ " <-- packet.getUserID() videoCCTV json data exception: " + e);//参数异常

            return;
        }

        String videoUrl = ResponseFactory.CrtRTMPUrl(DevIdx, "stream", 1);
        VideoServer videoServerQry = instance.getVideoServerQry(34);
        DebugLogger.info("videoUrl:" + videoUrl);
        Map<String, Object> map = new HashMap();
        map.put("UserName", UserName);
        map.put("protocolID", videoServerQry.getProtocolID());
        map.put("videoUrl", videoUrl);
        String valueJson = JSON.toJSONString(map);
        String str2 = "{\"devID\":\"" + DevIdx + "\",\"cmd\":\"" + Cmd.CMD_OUT_WEB_SOCKET_VIDEO_DETA + "\",\"value\":" + valueJson + "}";


        //开启音视频流   DeviceGetRTMPUrl

        try {
            deviceGetRTMPUrl(DevIdx, 0, videoUrl, "dailyInfo", false);
        } catch (UnsupportedEncodingException e) {
            DebugLogger.err(logger,packet.getUserID()+ " <-- packet.getUserID() deviceGetRTMPUrl: "+e);
            e.printStackTrace();
        }
        ResponseSendUtil.writeAndFlushWs(str2, ctx);


//        List<StaffInfo> staffData = BDMybais.getInstance().getStaffData(DevIdx);
//        for (StaffInfo staffDatum : staffData) {
//            DebugLogger.debug(staffDatum);
//            ChannelHandlerContext webSocket = ClientManager.getInstance().getWebSocket(staffDatum.getPolNo());
//            if (webSocket != null) {
//                System.err.println("发送webSocket 给调度台");
//                webSocket.channel().writeAndFlush(new TextWebSocketFrame(str));
////                webSocket.channel().writeAndFlush(new TextWebSocketFrame(str1));
//                webSocket.channel().writeAndFlush(new TextWebSocketFrame(str2));
//            }
//        }
    }

    //开启音视频流
    private void deviceGetRTMPUrl(int mydev_idx, int var, String RTMPUrl, String dailyInfo, boolean bSOS) throws UnsupportedEncodingException {
        byte[] rtmpByte = ByteUtil.intToBytes(1);// 4 byte, rtmp类型，0 音视频；1 视频；2 音频
        byte[] rtmpAdd = RTMPUrl.getBytes("GB2312");
        byte[] bytes = new byte[132];
        System.arraycopy(rtmpByte, 0, bytes, 0, rtmpByte.length);
        System.arraycopy(rtmpAdd, 0, bytes, 4, rtmpAdd.length);
        byte[] groupResponse = new byte[0];
        try {
            groupResponse = ResponseFactory.getListResponse(Cmd.CMD_OUT_UPLOADING_RTMP, (short) 1, mydev_idx, bytes);
        } catch (UnsupportedEncodingException e) {
            DebugLogger.err(logger,mydev_idx+ " <-- mydev_idx  ResponseFactory.getListResponse: "+e);
            e.printStackTrace();
        }
        if (bSOS) {

            if (bytes != null) {
                ResponseSendUtil.writeAndFlush(groupResponse, ctx);
            }
        } else {

            if (bytes != null) {
                DebugLogger.info("deviceGetRTMPUrl mydev_idx:" + mydev_idx);
                ChannelHandlerContext socketClient = ClientManager.getInstance().getSocketClient(String.valueOf(mydev_idx));
                if (socketClient != null) {
                    ResponseSendUtil.writeAndFlush(groupResponse, socketClient);
                }
            }
        }
    }


    private void serverGPS(Message packet) {
//        String value = (String) packet.getValue();
        String value = JSON.toJSONString(packet.getValue());
        JSONObject body = JSON.parseObject(value);
        Integer id = null;
        Integer type = 0;
        try {
            id = body.getInteger("devId");
            if (body.getInteger("type") == null) {
                type = 0;
            } else {
                type = body.getInteger("type");
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
            DebugLogger.err(logger, packet.getUserID()+ " <-- packet.getUserID() serverGPS json data exception: " + e);//参数异常
            return;
        }
        GpsQry gps = instance.getGpsQry(id);
        if (gps == null) {
            DebugLogger.err(logger,packet.getUserID()+ " <-- packet.getUserID() serverGPS mysql GPS is null"); //参数异常

            return;
        }

        Map<String, Object> map = new HashMap();
        map.put("devId", gps.getDev_idx());
        map.put("time", gps.getGPSDate());
        switch (type) {
            case 1:// 1：84
                map.put("lon", gps.getLon84());
                map.put("lat", gps.getLat84());
                break;
            case 2:// 2：百度
                map.put("lon", gps.getLongBD());
                map.put("lat", gps.getLatBD());
                break;
            case 3://  3：高德
                map.put("lon", gps.getLonGCJ());
                map.put("lat", gps.getLatGCJ());
                break;
            default:
                DebugLogger.info("GPS type  " + type);
                // 当expression不等于任何case值时执行的代码块
                break;
        }

        map.put("type", type);
        map.put("height", gps.getAltitude());
        map.put("speed", gps.getSpeed());
        map.put("angle", gps.getDirec());
        map.put("statellite", 4);
        map.put("isChina", 1);
        String valueJson = JSON.toJSONString(map);
        String str = "{\"devID\":\"" + gps.getDev_idx() + "\",\"cmd\":\"" + Cmd.CMD_OUT_WEB_SOCKET_SEND_GPS + "\",\"value\":" + valueJson + "}";
        DebugLogger.info(str);
//        ctx.channel().writeAndFlush(new TextWebSocketFrame(str));
        ResponseSendUtil.writeAndFlushWs(str, ctx);
    }

    private void videoCall(Message packet) {
        String value = JSON.toJSONString(packet.getValue());
        JSONObject body = JSON.parseObject(value);
        DebugLogger.info(body);
        String[] split = value.split(",");
        if (true) {
            String FuncType = null;
            String AudioType = null;
            int ID = 0;
            try {
                AudioType = body.getString("audioType");
                ID = body.getInteger("id");
                FuncType = body.getString("funcType");
            } catch (Exception e) {
                e.printStackTrace();
                DebugLogger.err(logger, packet.getUserID()+ " <-- packet.getUserID() videoCall json data exception: " + e);//参数异常

                return;
            }
            BDMybais instance = BDMybais.getInstance();
            WebRtc webRtc = new WebRtc();
            //获取服务  获取WebRTC
            VideoServer videoServerQry = this.instance.getVideoServerQry(51);
            //获取自己 调度台
            Users user = this.instance.getUser(packet.getUserID());
            String strUser = "[{\"devID\":\"" + packet.getUserID() + "\"},{\"cmd\":\"" + Cmd.CMD_OUT_WEB_SOCKET_VIDEO_CALL + "\"},{\"value\":\"" + webRtc.getTalkGrade() + "," + AudioType + "," + ID + "," + FuncType + "," + videoServerQry.getServerIP() + "," + videoServerQry.getPort() + "," + webRtc.getRoomID() + "," + webRtc.getUserName() + "\"}]";

            byte[] bytes = ByteUtil.shortToBytes(Short.parseShort(AudioType));//2字节，对象类型，0 群组；1 用户1
            byte[] bytes1 = ByteUtil.intToBytes(ID);//4 字节， 群组ID或者用户的ID
            byte[] bytes2 = ByteUtil.shortToBytes(Short.parseShort(FuncType));//2字节， 0 集群对讲；1 视频通话
            byte[] commandSend = new byte[0];

            String audioGroupName = null;
            if (AudioType.equals("0")) {
                webRtc.setUserID(webRtc.getUserID());
                webRtc = instance.getWedRTCSevaV2(webRtc);
                DebugLogger.info(webRtc.toString());
                List<Group> groups = this.instance.getgroupLog(ID);
                if (groups == null || groups.size() == 0) {
                    DebugLogger.err(logger,packet.getUserID()+ " <-- packet.getUserID() List<Group> groups: "+groups); //参数赋值异常
                } else {
                    audioGroupName = groups.get(0).getAudioGroupName();
                    //发给对方
                    try {
                        commandSend = ResponseFactory.getCommandSend(Cmd.CMD_OUT_OBJECT_WEDRTC_URL_PORT, (short) webRtc.getTalkGrade(), packet.getUserID(), webRtc, audioGroupName, videoServerQry, bytes, bytes1, bytes2);
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                        DebugLogger.err(logger,packet.getUserID()+ " <-- packet.getUserID() ResponseFactory.getCommandSend : "+e); //参数赋值异常


                    }

                    ChannelHandlerContext socketClient = null;
                    for (Group group : groups) {
                        socketClient = ClientManager.getInstance().getSocketClient(String.valueOf(group.getUdvId()));
                        if (socketClient != null) {
                            DebugLogger.info(group.getuName() + "->group");
                            ResponseSendUtil.writeAndFlush(commandSend, socketClient);
                        }
                    }
                }


            } else if (AudioType.equals("1")) {
                webRtc.setUserID(ID);
                webRtc = instance.getWedRTCSevaV2(webRtc);
                DebugLogger.info(webRtc.toString());
                ChannelHandlerContext socketClient = ClientManager.getInstance().getSocketClient(String.valueOf(webRtc.getDevicID()));
                if (socketClient != null) {
                    //发送对讲广播---------------------------------------------------------------------------
                    //发给对方
                    try {
                        commandSend = ResponseFactory.getCommandSend(Cmd.CMD_OUT_OBJECT_WEDRTC_URL_PORT, (short) webRtc.getTalkGrade(), ID, webRtc, user.getuName(), videoServerQry, bytes, bytes1, bytes2);
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                        DebugLogger.err(logger,packet.getUserID()+ " <-- packet.getUserID() ResponseFactory.getCommandSend 1: "+e); //参数赋值异常

                    }
                    ResponseSendUtil.writeAndFlush(commandSend, socketClient);


                }
            }

            //发给自己

            Map<String, Object> map = new HashMap<>();
            map.put("talkGrade", 1);
            map.put("audioType", AudioType);
            map.put("id", ID);
            map.put("funcType", FuncType);
            map.put("audioIp", videoServerQry.getServerIP());
            map.put("audioPort", videoServerQry.getPort());
            map.put("roomId", webRtc.getRoomID());
            if (AudioType.equals("0")) {
                map.put("talkToUserName", audioGroupName);

            } else if (AudioType.equals("1")) {
                map.put("talkToUserName", webRtc.getUserName());

            }

            String valueJson = JSON.toJSONString(map);
            String strMy = null;
            if (AudioType.equals("0")) {

                strMy = "{\"devID\":\"" + packet.getUserID() + "\",\"cmd\":\"" + Cmd.CMD_OUT_WEB_SOCKET_VIDEO_CALL + "\",\"value\":" + valueJson + "}";
            } else if (AudioType.equals("1")) {

                strMy = "{\"devID\":\"" + webRtc.getDevicID() + "\",\"cmd\":\"" + Cmd.CMD_OUT_WEB_SOCKET_VIDEO_CALL + "\",\"value\":" + valueJson + "}";
            }

            DebugLogger.info(strMy + "    strMy");
            ResponseSendUtil.writeAndFlushWs(strMy, ctx);

        }
    }

    /**
     *
     */
    private void join_quit(Message packet, Integer Operat) {
        if (Operat == 1) {
            join_quitWebRTC(packet);
        } else if (Operat == 0) {
            quitWebRTC(packet);
        } else {
            DebugLogger.err(logger,packet.getUserID()+ " <-- packet.getUserID() join_quit Operat else");
        }
    }

    /**
     * 加入WebRTC房间
     */
    private void join_quitWebRTC(Message packet) {
        DebugLogger.info("加入WebRTC房间_WS");
        String value = JSON.toJSONString(packet.getValue());
        JSONObject body = JSON.parseObject(value);
        String roomID = body.getString("roomId");
        int userID = packet.getUserID();
        DebugLogger.info(roomID + "set房间号join_quitWebRTC");
        DebugLogger.info(userID + "set房间号的用户id");
        RTCAddRoom rtcAddRoom = new RTCAddRoom();
        rtcAddRoom.setUserID(userID);
        rtcAddRoom.setRoomID(Integer.parseInt(roomID));
//        RTCAddRoom rtcAddRoom1 = this.instance.getRTCAddRoom(rtcAddRoom);
        RTCAddRoom rtcAddRoom1 = this.instance.getRTCAddRoomV2(rtcAddRoom);
        DebugLogger.info(rtcAddRoom1);
        ClientManager.getInstance().setRtcRoom(roomID, userID);
    }

    /**
     * 退出WebRTC房间
     */
    private void quitWebRTC(Message packet) {
        DebugLogger.info("退出WebRTC房间_WS");
        String value = JSON.toJSONString(packet.getValue());
        JSONObject body = JSON.parseObject(value);
        String roomID = body.getString("roomId");
        int cmd = packet.getCmd();
        int userID = packet.getUserID();
        DebugLogger.info(roomID + "_WS");

        RTCAddRoom rtcAddRoom = new RTCAddRoom();
        rtcAddRoom.setUserID(userID);
        rtcAddRoom.setRoomID(Integer.parseInt(roomID));
        RTCAddRoom rtcAddRoom1 = this.instance.getRTCDelRoomV2(rtcAddRoom);
//        ClientManager.getInstance().setRtcRoom(roomID,userID);
    }

    private void shootFileList(Message packet) {
        DebugLogger.info(packet.getValue() + "--->packet.getValue()");
        String value = JSON.toJSONString(packet.getValue());
        JSONObject body = JSON.parseObject(value);
        Integer devId = body.getInteger("devId");
        Users user = BDMybais.getInstance().getUser(packet.getUserID());
        //TODO 提取 ---------------------------------
        WebSocketInfo webSocketInfo = ClientManager.getInstance().getWebSocketInfo(user.getuLoginName());
        if (webSocketInfo == null) {
            DebugLogger.err(logger, packet.getUserID()+ " <-- packet.getUserID() shootFileList webSocketInfo == null");
            return;
        }
        CopyOnWriteArrayList<String> devFileMatching = ClientManager.getInstance().getDevFileMatching(devId);
        if (devFileMatching != null && devFileMatching.size() > 0) {
            ParserSend.sendFileList(devId,user.getuLoginName(), devFileMatching,
            ParserSend.SendTargetType.SPECIFIC_USER, ctx);
            return;
        }

        byte[] response = ResponseFactory.getResponse(Cmd.CMD_OUT_PHOTOG_FILE_LIST, (short) 0, devId);
        ChannelHandlerContext socketClient = ClientManager.getInstance().getSocketClient(String.valueOf(devId));
        if (socketClient == null) {
            DebugLogger.err(logger, packet.getUserID()+ " <-- packet.getUserID() device is null socketClient"); //设备不存在
            return;
        }
        ResponseSendUtil.writeAndFlush(response, socketClient);
        //TODO 获取调度台信息并且更新调度台信息
        webSocketInfo.setFileSize(0);
        webSocketInfo.setFileDevId(String.valueOf(devId));
        ClientManager.getInstance().updateWebSocketInfo(user.getuLoginName(), webSocketInfo);

    }

    private void closeFileList(Message packet) {
        int userID = packet.getUserID();
        Users user = BDMybais.getInstance().getUser(userID);
        DebugLogger.info(packet.getValue() + "--->packet.getValue()");
        String value = JSON.toJSONString(packet.getValue());
        JSONObject body = JSON.parseObject(value);
        Integer devId = body.getInteger("devId");
        if(user == null){
            DebugLogger.err(logger,packet.getUserID()+ " <-- packet.getUserID() closeFileList is user no: "+user);
            Map<String, Object> map = new HashMap<>();

            map.put("devId", 0);
            map.put("devNo", null);
            map.put("userName", null);
            map.put("state", 0);
            String valueJson = JSON.toJSONString(map);
            String strMy = "{\"devID\":\"" + devId + "\",\"cmd\":\"" + Cmd.CMD_OUT_WEB_CLOSE_FILE_LIST + "\",\"value\":" + valueJson + "}";
            ResponseSendUtil.writeAndFlushWs(strMy, ctx);
            return;
        }
        WebSocketInfo webSocketInfo = ClientManager.getInstance().getWebSocketInfo(user.getuLoginName());
        if(webSocketInfo!= null){
            webSocketInfo.setFileSize(0);
            webSocketInfo.setFileDevId(null);
            ClientManager.getInstance().updateWebSocketInfo(user.getuLoginName(),webSocketInfo);
            DeviceInfo onlineMemberByClientId = ClientManager.getInstance().getOnlineMemberByClientId(String.valueOf(devId));
            if(onlineMemberByClientId == null){
                DebugLogger.err(logger,packet.getUserID()+ " <-- packet.getUserID() closeFileList is onlineMemberByClientId no: "+devId);
                Map<String, Object> map = new HashMap<>();
                map.put("devId", 0);
                map.put("devNo", null);
                map.put("userName", user.getuName());
                map.put("state", 0);
                String valueJson = JSON.toJSONString(map);
                String strMy = "{\"devID\":\"" + devId + "\",\"cmd\":\"" + Cmd.CMD_OUT_WEB_CLOSE_FILE_LIST + "\",\"value\":" + valueJson + "}";
                ResponseSendUtil.writeAndFlushWs(strMy, ctx);
                return;
            } else {
                ClientManager.getInstance().delDevFileList(devId);
                DebugLogger.info("closeFileList is delDevFileList yes:"+devId);
                Map<String, Object> map = new HashMap<>();
                map.put("devId", devId);
                map.put("devNo", onlineMemberByClientId.getDeviceNo());
                map.put("userName", user.getuName());
                map.put("state", 1);
                String valueJson = JSON.toJSONString(map);
                String strMy = "{\"devID\":\"" + devId + "\",\"cmd\":\"" + Cmd.CMD_OUT_WEB_CLOSE_FILE_LIST + "\",\"value\":" + valueJson + "}";
                ResponseSendUtil.writeAndFlushWs(strMy, ctx);
                return;
            }
        } else {
            DebugLogger.err(logger,packet.getUserID()+ " <-- packet.getUserID() closeFileList is webSocketInfo no: "+webSocketInfo);
        }
    }

    private void putFileList(Message packet) throws UnsupportedEncodingException {

        String value = JSON.toJSONString(packet.getValue());
        JSONObject body = JSON.parseObject(value);
        Integer devId = body.getInteger("devId");
        String files = body.getString("files");
        String valueBy = files;
        DebugLogger.info(valueBy);


        byte[] bytes = valueBy.getBytes("GB2312");
        byte[] response = ResponseFactory.getListResponse(Cmd.CMD_OUT_UPGRADE_FILE_LIST, (short) 0, packet.getUserID(), bytes);
//        Integer devid = ClientManager.getInstance().getUserFileMatching(packet.getUserID());
        ChannelHandlerContext socketClient = ClientManager.getInstance().getSocketClient(String.valueOf(devId));
        if (socketClient == null) {
            DebugLogger.err(logger, packet.getUserID()+ " <-- packet.getUserID() putFileList socketClient: " + socketClient);
            return;
        }
        ResponseSendUtil.writeAndFlush(response, socketClient);
    }
}
